{% extends "base.html" %}

{% block title %}健康追踪 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1><i class="bi bi-heart-pulse"></i> 健康习惯追踪</h1>
            <p class="text-muted">培养良好习惯，记录每日进步</p>
        </div>
        <button class="btn btn-primary btn-custom" data-bs-toggle="modal" data-bs-target="#addHabitModal">
            <i class="bi bi-plus-circle"></i> 添加习惯
        </button>
    </div>
</div>

<!-- 今日概览 -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-primary" id="stat-total-habits">0</h3>
                <p class="text-muted mb-0">总习惯数</p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-success" id="stat-today-checked">0</h3>
                <p class="text-muted mb-0">今日已打卡</p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-warning" id="stat-completion-rate">0%</h3>
                <p class="text-muted mb-0">今日完成率</p>
            </div>
        </div>
    </div>
</div>

<!-- 今日打卡 -->
<div class="card mb-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><i class="bi bi-calendar-check"></i> 今日打卡</h5>
    </div>
    <div class="card-body">
        <div id="today-checkins" class="row">
            <p class="text-center text-muted">加载中...</p>
        </div>
    </div>
</div>

<!-- 习惯列表 -->
<div class="card">
    <div class="card-header bg-secondary text-white">
        <h5 class="mb-0"><i class="bi bi-list-ul"></i> 我的习惯</h5>
    </div>
    <div class="card-body">
        <div id="habits-list">
            <p class="text-center text-muted">加载中...</p>
        </div>
    </div>
</div>

<!-- 添加习惯模态框 -->
<div class="modal fade" id="addHabitModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加习惯</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="add-habit-form">
                    <div class="mb-3">
                        <label class="form-label">习惯名称 *</label>
                        <input type="text" class="form-control" id="habit-name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="habit-description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">图标</label>
                        <div class="d-flex gap-2 flex-wrap" id="add-icon-container">
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('🏃')">🏃</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('💧')">💧</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('😴')">😴</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('📚')">📚</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('🧘')">🧘</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('🥗')">🥗</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('💪')">💪</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectIcon('✍️')">✍️</button>
                        </div>
                        <input type="hidden" id="habit-icon" value="📝">
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">每日目标</label>
                            <input type="number" class="form-control" id="habit-target" value="1" min="1">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">单位</label>
                            <select class="form-select" id="habit-unit">
                                <option value="次">次</option>
                                <option value="杯">杯</option>
                                <option value="分钟">分钟</option>
                                <option value="小时">小时</option>
                                <option value="千米">千米</option>
                                <option value="页">页</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addHabit()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑习惯模态框 -->
<div class="modal fade" id="editHabitModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑习惯</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="edit-habit-form">
                    <input type="hidden" id="edit-habit-id">
                    <div class="mb-3">
                        <label class="form-label">习惯名称 *</label>
                        <input type="text" class="form-control" id="edit-habit-name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="edit-habit-description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">图标</label>
                        <div class="d-flex gap-2 flex-wrap" id="edit-icon-container">
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('🏃')">🏃</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('💧')">💧</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('😴')">😴</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('📚')">📚</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('🧘')">🧘</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('🥗')">🥗</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('💪')">💪</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg icon-selector" onclick="selectEditIcon('✍️')">✍️</button>
                        </div>
                        <input type="hidden" id="edit-habit-icon" value="📝">
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">每日目标</label>
                            <input type="number" class="form-control" id="edit-habit-target" value="1" min="1">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">单位</label>
                            <select class="form-select" id="edit-habit-unit">
                                <option value="次">次</option>
                                <option value="杯">杯</option>
                                <option value="分钟">分钟</option>
                                <option value="小时">小时</option>
                                <option value="千米">千米</option>
                                <option value="页">页</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateHabit()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 习惯统计模态框 -->
<div class="modal fade" id="statsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><span id="stats-habit-icon"></span> <span id="stats-habit-name"></span> 统计</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row text-center mb-4">
                    <div class="col-md-3">
                        <div class="p-3 border rounded">
                            <h3 class="text-primary" id="stats-total-days">0</h3>
                            <p class="text-muted mb-0">总打卡天数</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border rounded">
                            <h3 class="text-success" id="stats-streak">0</h3>
                            <p class="text-muted mb-0">连续打卡</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border rounded">
                            <h3 class="text-warning" id="stats-week-completion">0%</h3>
                            <p class="text-muted mb-0">本周完成率</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border rounded">
                            <h3 class="text-info" id="stats-month-completion">0%</h3>
                            <p class="text-muted mb-0">本月完成率</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentHabits = [];
let selectedIcon = '📝';
let selectedEditIcon = '📝'; // 编辑时选择的图标

// 选择图标（添加习惯时）
function selectIcon(icon) {
    selectedIcon = icon;
    document.getElementById('habit-icon').value = icon;
    
    // 移除所有选中状态
    document.querySelectorAll('#add-icon-container .icon-selector').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // 添加当前选中状态
    event.target.classList.add('selected');
}

// 选择图标（编辑习惯时）
function selectEditIcon(icon) {
    selectedEditIcon = icon;
    document.getElementById('edit-habit-icon').value = icon;
    
    // 移除所有选中状态
    document.querySelectorAll('#edit-icon-container .icon-selector').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // 添加当前选中状态
    event.target.classList.add('selected');
}

// 加载仪表板
function loadDashboard() {
    fetch('/health/api/dashboard')
        .then(response => response.json())
        .then(data => {
            // 更新统计
            document.getElementById('stat-total-habits').textContent = data.total_habits;
            
            const checkedCount = data.today_checkins.filter(c => c.checked).length;
            document.getElementById('stat-today-checked').textContent = checkedCount;
            
            const completionRate = data.total_habits > 0 
                ? Math.round((checkedCount / data.total_habits) * 100) 
                : 0;
            document.getElementById('stat-completion-rate').textContent = completionRate + '%';
            
            // 渲染今日打卡
            renderTodayCheckins(data.today_checkins);
        });
}

// 渲染今日打卡
function renderTodayCheckins(checkins) {
    const container = document.getElementById('today-checkins');
    
    if (checkins.length === 0) {
        container.innerHTML = '<p class="text-center text-muted col-12">暂无习惯</p>';
        return;
    }
    
    container.innerHTML = checkins.map(item => {
        const habit = item.habit;
        const currentCount = item.count;
        const targetCount = habit.target_count;
        const isCompleted = currentCount >= targetCount;
        const hasStarted = currentCount > 0;
        
        // 根据完成状态设置样式
        let cardClass = 'border-secondary';
        let progressHtml = '';
        let buttonHtml = '';
        
        if (isCompleted) {
            cardClass = 'border-success bg-success bg-opacity-10';
            progressHtml = `
                <div class="mt-2">
                    <span class="badge bg-success">
                        <i class="bi bi-check-circle-fill"></i> 已完成 ${currentCount}/${targetCount}${habit.unit}
                    </span>
                </div>`;
            // 已完成也可以继续打卡
            buttonHtml = `
                <button class="btn btn-sm btn-outline-success mt-2" onclick="checkinHabit(${habit.id})">
                    <i class="bi bi-plus-circle"></i> 再来一次
                </button>`;
        } else if (hasStarted) {
            cardClass = 'border-warning bg-warning bg-opacity-10';
            progressHtml = `
                <div class="mt-2">
                    <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-warning" role="progressbar" 
                             style="width: ${(currentCount/targetCount)*100}%"></div>
                    </div>
                    <small class="text-muted">${currentCount}/${targetCount}${habit.unit}</small>
                </div>`;
            buttonHtml = `
                <button class="btn btn-sm btn-warning mt-2" onclick="checkinHabit(${habit.id})">
                    <i class="bi bi-plus-circle"></i> +1 打卡
                </button>`;
        } else {
            progressHtml = `<small class="text-muted">目标: ${targetCount}${habit.unit}</small>`;
            buttonHtml = `
                <button class="btn btn-sm btn-primary mt-2" onclick="checkinHabit(${habit.id})">
                    <i class="bi bi-check-circle"></i> 打卡
                </button>`;
        }
        
        return `
            <div class="col-md-4 mb-3">
                <div class="card ${cardClass} h-100">
                    <div class="card-body text-center">
                        <div style="font-size: 3rem;">${habit.icon}</div>
                        <h6 class="mt-2 mb-1">${habit.name}</h6>
                        ${progressHtml}
                        ${buttonHtml}
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 加载习惯列表
function loadHabits() {
    fetch('/health/api/habits')
        .then(response => response.json())
        .then(data => {
            currentHabits = data.habits;
            renderHabits();
        });
}

// 渲染习惯列表
function renderHabits() {
    const container = document.getElementById('habits-list');
    
    if (currentHabits.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">暂无习惯，点击右上角添加</p>';
        return;
    }
    
    container.innerHTML = currentHabits.map(habit => `
        <div class="d-flex justify-content-between align-items-center border-bottom py-3">
            <div class="d-flex align-items-center">
                <div style="font-size: 2rem;" class="me-3">${habit.icon}</div>
                <div>
                    <h6 class="mb-1">${habit.name}</h6>
                    <small class="text-muted">${habit.description || '无描述'} · 目标: ${habit.target_count}${habit.unit}/天</small>
                </div>
            </div>
            <div>
                <button class="btn btn-sm btn-outline-info" onclick="viewStats(${habit.id})">
                    <i class="bi bi-bar-chart"></i> 统计
                </button>
                <button class="btn btn-sm btn-outline-primary" onclick="editHabit(${habit.id})">
                    <i class="bi bi-pencil"></i> 编辑
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteHabit(${habit.id})">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        </div>
    `).join('');
}

// 添加习惯
function addHabit() {
    const data = {
        name: document.getElementById('habit-name').value,
        description: document.getElementById('habit-description').value,
        icon: document.getElementById('habit-icon').value,
        target_count: parseInt(document.getElementById('habit-target').value),
        unit: document.getElementById('habit-unit').value
    };
    
    if (!data.name) {
        showAlert('请输入习惯名称', 'warning');
        return;
    }
    
    fetch('/health/api/habits', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('添加成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addHabitModal')).hide();
            document.getElementById('add-habit-form').reset();
            selectedIcon = '📝';
            
            // 清除图标选中状态
            document.querySelectorAll('#add-icon-container .icon-selector').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            loadHabits();
            loadDashboard();
        }
    });
}

// 打卡习惯
function checkinHabit(habitId) {
    fetch(`/health/api/habits/${habitId}/checkin`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({})
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('打卡成功！', 'success');
            loadDashboard();
        }
    });
}

// 查看统计
function viewStats(habitId) {
    const habit = currentHabits.find(h => h.id === habitId);
    if (!habit) return;
    
    document.getElementById('stats-habit-icon').textContent = habit.icon;
    document.getElementById('stats-habit-name').textContent = habit.name;
    
    fetch(`/health/api/habits/${habitId}/stats`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('stats-total-days').textContent = data.total_days;
            document.getElementById('stats-streak').textContent = data.streak;
            document.getElementById('stats-week-completion').textContent = data.week_completion + '%';
            document.getElementById('stats-month-completion').textContent = data.month_completion + '%';
            
            new bootstrap.Modal(document.getElementById('statsModal')).show();
        });
}

// 编辑习惯
function editHabit(habitId) {
    const habit = currentHabits.find(h => h.id === habitId);
    if (!habit) return;
    
    // 填充表单
    document.getElementById('edit-habit-id').value = habit.id;
    document.getElementById('edit-habit-name').value = habit.name;
    document.getElementById('edit-habit-description').value = habit.description || '';
    document.getElementById('edit-habit-icon').value = habit.icon;
    document.getElementById('edit-habit-target').value = habit.target_count;
    document.getElementById('edit-habit-unit').value = habit.unit;
    selectedEditIcon = habit.icon;
    
    // 移除所有选中状态并高亮当前图标
    document.querySelectorAll('#edit-icon-container .icon-selector').forEach(btn => {
        btn.classList.remove('selected');
        if (btn.textContent === habit.icon) {
            btn.classList.add('selected');
        }
    });
    
    // 显示模态框
    new bootstrap.Modal(document.getElementById('editHabitModal')).show();
}

// 更新习惯
function updateHabit() {
    const habitId = document.getElementById('edit-habit-id').value;
    const data = {
        name: document.getElementById('edit-habit-name').value,
        description: document.getElementById('edit-habit-description').value,
        icon: document.getElementById('edit-habit-icon').value,
        target_count: parseInt(document.getElementById('edit-habit-target').value),
        unit: document.getElementById('edit-habit-unit').value
    };
    
    if (!data.name) {
        showAlert('请输入习惯名称', 'warning');
        return;
    }
    
    fetch(`/health/api/habits/${habitId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('editHabitModal')).hide();
            
            // 清除图标选中状态
            document.querySelectorAll('#edit-icon-container .icon-selector').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            loadHabits();
            loadDashboard();
        }
    });
}

// 删除习惯
function deleteHabit(habitId) {
    if (!confirm('确定要删除这个习惯吗？所有打卡记录也会被删除。')) return;
    
    fetch(`/health/api/habits/${habitId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            loadHabits();
            loadDashboard();
        }
    });
}

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    loadHabits();
    loadDashboard();
});
</script>
{% endblock %}

